import java.util.PriorityQueue;
class MyTimerTask implements Comparable<MyTimerTask>{
    private long time;
    private Runnable runnable;
    public MyTimerTask(Runnable task,long delay) {
        this.runnable = task;
        this.time = System.currentTimeMillis()+delay;
    }

    public long getTime() {
        return time;
    }

    public void run() {
        runnable.run();
    }

    @Override
    public int compareTo(MyTimerTask o) {
        return (int)(this.time -o.getTime());
    }
}
class MyTimer {
    private PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();
    private final Object locker = new Object();
    public MyTimer(){
        Thread thread = new Thread(() -> {
            while (true) {
                synchronized (locker) {
                    //直至拿到非空的任务
                    MyTimerTask task = queue.peek();
                    while (task == null) {
                        try {
                            locker.wait();
                            task = queue.peek();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }

                    //判定时间到了没
                    if (System.currentTimeMillis() >= task.getTime()) {
                        task.run();
                        queue.poll();
                    }else {
                        try {
                            locker.wait(task.getTime() - System.currentTimeMillis());
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }

        });
        thread.start();
    }

    //放入任务
    public void schedule(Runnable runnable,long delay) {
        synchronized (locker) {
            MyTimerTask task = new MyTimerTask(runnable,delay);
            queue.add(task);
            locker.notify();
        }
    }

    //终止此计时器
    public void cancel() {
        //xxxx
    }

}
public class Demo2{
    public static void main(String[] args) throws InterruptedException {
        MyTimer mytimer = new MyTimer();
        mytimer.schedule(() -> {
            System.out.println("3000");
        },3000);
        mytimer.schedule(() -> {
            System.out.println("2000");
        },2000);
        mytimer.schedule(() -> {
            System.out.println("1000");
        },1000);

        Thread.sleep(4000);
        //mytimer.cancel();
    }
}
